package service;

import java.util.Iterator;
import java.util.LinkedList;

import util.RegexUtil;
import dao.MovieDAO;
import domain.Movie;
import ex.DatabaseException;
import ex.ProjectCompositionFailedException;
import ex.RegistrationFailedException;

public class MovieService {
	private static int TOP_MOVIE_NUMBER = 5;
	MovieDAO movieDao=new MovieDAO();
	
	public Movie getMovieByMid(long mid) throws DatabaseException
	{
		return movieDao.selectMovieByMid(mid);
	}
	public void createMovie(Movie movie) throws DatabaseException, ProjectCompositionFailedException
	{
		if(movie!=null){
			if(RegexUtil.isNullOrEmpty(movie.getName())){
				throw new ProjectCompositionFailedException("You must enter project name!");
			}
			if(RegexUtil.isNullOrEmpty(movie.getSummary())){
				throw new ProjectCompositionFailedException("You must enter description between 50 and 500 characters!");
			}
			if(RegexUtil.isNullOrEmpty(movie.getGenre())){
				throw new ProjectCompositionFailedException("You must enter genre!");
			}
			movieDao.insertMovie(movie);
		}		
	}
	public Movie getLastAddedMovie() throws DatabaseException {
		return movieDao.selectLastMovie();
	}	
	
	public LinkedList<Movie> getTopMovies() throws DatabaseException {
		LinkedList<Movie> topMovies = new LinkedList<Movie>();
		LinkedList<Movie> topMoviesWithCast = new LinkedList<Movie>();
		topMovies =  movieDao.selectTopMovies(TOP_MOVIE_NUMBER);
		Iterator<Movie> itr = topMovies.iterator();
		while(itr.hasNext()){
			topMoviesWithCast.add(movieDao.selectMovieByMid(itr.next().getMid()));
		}
		return topMoviesWithCast;
	}	
	
	public LinkedList<Movie> getLatestMovies() throws DatabaseException {
		LinkedList<Movie> latestMovies = new LinkedList<Movie>();
		LinkedList<Movie> latestMoviesWithCast = new LinkedList<Movie>();
		latestMovies =  movieDao.selectLatestMovies(TOP_MOVIE_NUMBER);
		Iterator<Movie> itr = latestMovies.iterator();
		while(itr.hasNext()){
			latestMoviesWithCast.add(movieDao.selectMovieByMid(itr.next().getMid()));
		}
		return latestMoviesWithCast;
	}	
}